package com.apes.scm.masterdata.frame.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.plugin.mq.annotation.Consumer;
import com.apes.framework.rop.converter.DateUtils;
import com.apes.framework.util.EventUtil;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.*;
import com.apes.scm.masterdata.frame.repository.*;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.stock.model.Depot;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.model.PhyDepot;
import com.apes.scm.masterdata.stock.model.StockUsage;
import com.apes.scm.masterdata.stock.repository.DepotRepository;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.masterdata.stock.repository.PhyDepotRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("branchEntryService")
public class BranchEntryService extends DomainService {
    @Autowired
    private BranchEntryRepository branchEntryRepository;

    @Autowired
    PartyRoleRepository partyRoleRepository;

    @Autowired
    BranchRepository branchRepository;
    @Autowired
    DeptRepository deptRepository;
    @Autowired
    DepotRepository depotRepository;
    @Autowired
    SequenceService sequenceService;
    @Autowired
    AreaRepository areaRepository;
    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    LocationRepository locationRepository;
    @Autowired
    DutyCenterRepository dutyCenterRepository;
    @Autowired
    StoreRepository storeRepository;
    @Value("${apes.switched:false}")
    private Boolean switched;

    public BranchEntry save(SimpleRequest request) {
        BranchEntry branchEntry = request.getO(BranchEntry.class);
//        if (branchRepository.findOne(branchEntry.getCode())!=null){
//            throw new RuntimeException("门店【" + branchEntry.getCode() + "】在系统中已存在。");
//        }
        if (storeRepository.findAll(JpaDsl.toCriteriaByEq("code", branchEntry.getCode())).stream().count() > 0) {
            throw new RuntimeException("门店【" + branchEntry.getCode() + "】在系统中已存在。");
        }
        // 获取注册区县
        Area county = branchEntry.getCounty();// 注册地址.区县
        // 获取注册城市编码
        String cityId = county.getParent();
        // 查找注册城市
        Area city = areaRepository.findOne(cityId);
        branchEntry.setCity(city); // 注册地址.城市
        // 设置注册城市
        String provinceId = city.getParent();
        Area province = areaRepository.findOne(provinceId);
        branchEntry.setProvince(province); //注册地址.省份
        branchEntry.setState("create");
        branchEntry = branchEntryRepository.saveAndFlush(branchEntry);
        return branchEntry;
    }


    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<BranchEntry> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        return branchEntryRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 下拉查询
     *
     * @param request
     * @return
     * @throws Exception
     */
//    public Page<BranchEntry> find(SimpleRequest request) {
//        return branchEntryRepository.find(request.get("key"), PageRequest.of(request.get("page"), request.get("size")));
//    }
    public BranchEntry update(SimpleRequest request) {
        BranchEntry branchEntry = request.getO(BranchEntry.class);
        if (storeRepository.findAll(JpaDsl.toCriteriaByEq("code", branchEntry.getCode())).stream().count() > 0) {
            throw new RuntimeException("门店【" + branchEntry.getCode() + "】在系统中已存在。");
        }
        // 获取注册区县
        Area county = branchEntry.getCounty();// 注册地址.区县
        // 获取注册城市编码
        String cityId = county.getParent();
        // 查找注册城市
        Area city = areaRepository.findOne(cityId);
        branchEntry.setCity(city); // 注册地址.城市
        // 设置注册城市
        String provinceId = city.getParent();
        Area province = areaRepository.findOne(provinceId);
        branchEntry.setProvince(province); //注册地址.省份
        return branchEntryRepository.saveAndFlush(branchEntry);
    }

    public BranchEntry delete(SimpleRequest request) throws Exception {
        String id = request.get("id");
        Integer versions = request.get("version");

        BranchEntry branchEntry = branchEntryRepository.findOne(id);
        if (branchEntry == null) throw new RuntimeException("开店申请【" + id + "】在系统中不存在。");
        if (branchEntry.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
//        branchEntryRepository.delete(BranchEntry);
        branchEntry.setState("delete");
        return branchEntryRepository.saveAndFlush(branchEntry);


    }

    public BranchEntry findOne(String id) {
        return branchEntryRepository.findOne(id);
    }

    /**
     * 根据开店申请 生成 行政部门 业务部门 门店
     * 仓库 以及选择的库区属性生成对应的
     * 库区 并同步旧框架
     *
     * @param request
     */
    public BranchEntry setBranchAndDept(SimpleRequest request) {
        BranchEntry branchEntry = request.getO(BranchEntry.class);
        branchEntry = branchEntryRepository.findOne(branchEntry.getId());

        //写入业务部门
        Dept dept = setDept(branchEntry);
        //写入行政部门
        Branch branch = setBranch(branchEntry,dept);
        branchEntry.setState("approve");
        branchEntry = branchEntryRepository.saveAndFlush(branchEntry);
        //写入门店
        Store store = setStore(branchEntry, dept);
        //写入物理仓库
        PhyDepot phyDepot = setPhyDepot(store);
        //写入逻辑仓库
        Depot depot = setDepot(branchEntry, dept);
        branchEntry.setDepotId(depot.getId());
        //写入库区
        List<Location> locations = setLocations(branchEntry, depot, phyDepot);
        branchEntry.setLocations(locations);
        //生成本地权限 生成 本地角色 并同步到 旧框架
        // (2020-4-28修改 原代码未写同步至旧框架 原因不明 特将执行顺序放在同步方法前 如有添加权限同步 需将代码后置 )
        setLocalPermit(branchEntry);
//        生成成本中心 和 利润中心 (未写入新系统，原因未知)
//        setDutyCenter(branchEntry, dept);

        //产生同步至旧系统的body值
        JSONObject body = new JSONObject();
        //写入库区  DC
        writeLocations(branchEntry, locations, body);
        //写入部门
        writeBranch(branchEntry, branch, body);
        //写入地点
        writeLocation(branchEntry, body);
        //写入门店
        writeStore(branchEntry, store, body);
        //写入仓库扩展信息
        writeWarehouse(branchEntry, store, body);
        //写入采购信息
        writePurchase(branchEntry, body);
        //写入成本中心 和 利润中心
        writeDutyCenter(branchEntry, dept, body);
        //写入销售组织门店
        writeSalesStore(branchEntry, store, body);
        //同步方法
//        synUnifiedExport(body);
        MQUtil.publish("mq.branch.unified.export","开店申请", body);
        return branchEntry;
    }

    /**
     * 生成行政部门
     *
     * @param branchEntry
     */
    public Branch setBranch(BranchEntry branchEntry,Dept dept) {
        Branch branch = new Branch();
        branch.setId( dept.getId());
        Enumeration branchType = new Enumeration();
        branchType.setId("000007");
        branch.setBranchType(branchType);
        branch.setName(branchEntry.getName());
        branch.setParents(branchEntry.getParents());
        branch.setLevels(branchEntry.getLevels());
        branch.setLastStage(true);
        branch.setOrigin(branchEntry.getCode());
        branch.setValid(branchEntry.isValid());
        branch.setOpenDay(branchEntry.getOpenDay());
        Branch result = branchRepository.saveAndFlush(branch);
        branchEntry.setBranchId(result.getId());
        dept.setBranch(result);
        deptRepository.saveAndFlush(dept);
        return result;
    }

    /**
     * 生成业务部门
     *
     * @param branchEntry
     */
    public Dept setDept(BranchEntry branchEntry) {
        Dept dept = new Dept();
        dept.setName(branchEntry.getName());
//        dept.setBranch(branchRepository.findOne(branchEntry.getBranchId()));
        dept.setCompany(branchEntry.getCompany());
        dept.setProfitCenterId(branchEntry.getProfitCenterId());
        dept.setCostCenterId(branchEntry.getCostCenterId());
        dept.setValid(branchEntry.isValid());
        dept.addDeptType(DeptEnum.RETAIL);
        dept.addDeptType(DeptEnum.SALE);
        dept.addDeptType(DeptEnum.PURCHASE);
        dept.setId(dept.obtainDeptId(dept));
        dept.setOrigin(branchEntry.getCode());
        dept = deptRepository.saveAndFlush(dept);
        branchEntry.setDeptId(dept.getId());
        return dept;
    }

    /**
     * 写入门店信息
     *
     * @param branchEntry
     * @param dept
     * @return
     */
    public Store setStore(BranchEntry branchEntry, Dept dept) {
        Store store = new Store();
        store.setId(dept.getId());
        store.setCode(branchEntry.getCode());
        store.setName(branchEntry.getName());
        store.setBranchEntry(branchEntry);
        store.setDept(dept);
        store.setCompany(branchEntry.getCompany());
        store.setStoreType(branchEntry.getStoreType());
        store.setStoreLevels(branchEntry.getStoreLevels());
        store.setBusinessCircle(branchEntry.getBusinessCircle());
        store.setStoreSpace(branchEntry.getStoreSpace());
        store.setCountry(branchEntry.getCountry());
        store.setAddress(branchEntry.getAddress());
        store.setTelephone(branchEntry.getTelephone());
        store.setBoutiqueRoom(branchEntry.getBoutiqueRoom());
        store.setWarehouse(branchEntry.getWarehouse());
        store.setRentalArea(branchEntry.getRentalArea());
        store.setCalculationRental(branchEntry.getCalculationRental());
        store.setReceivingDay(branchEntry.getReceivingDay());
        store.setOpenDay(branchEntry.getOpenDay());
        store.setBannerLength(branchEntry.getBannerLength());
        store.setLEDLength(branchEntry.getLEDLength());
        store.setDecoration(branchEntry.getDecoration());
        store.setEquipment(branchEntry.getEquipment());
        store.setLatitude(branchEntry.getLatitude());
        store.setLongitude(branchEntry.getLongitude());
        store.setOpenPreheatDay(branchEntry.getOpenPreheatDay());
        store.setBusinessDay(branchEntry.getBusinessDay());
        store.setBusinessDayEnd(branchEntry.getBusinessDayEnd());
        store.setClosingDay(branchEntry.getClosingDay());
        store.setLogo(branchEntry.getLogo());
        store.setOrigin(branchEntry.getCode());
        store.setOutsourcingApproval(enumerationRepository.findOne("002305"));
        // 获取注册区县
        Area county = branchEntry.getCounty();// 注册地址.区县
        store.setCounty(county);
        // 获取注册城市编码
        String cityId = county.getParent();
        // 查找注册城市
        Area city = areaRepository.findOne(cityId);
        store.setCity(city); // 注册地址.城市
        // 设置注册城市
        String provinceId = city.getParent();
        Area province = areaRepository.findOne(provinceId);
        store.setProvince(province); //注册地址.省份
        List<Station> stations = new ArrayList<>();
        for (StationEntry stationEntry : branchEntry.getStations()) {
            Station station = new Station();
            station.setStore(store);
            station.setArea(stationEntry.getArea());
            station.setNote(stationEntry.getNote());
            station.setStationType(stationEntry.getStationType());
            station.setWorkNum(stationEntry.getWorkNum());
            stations.add(station);
        }

        store.setStations(stations);
        return storeRepository.saveAndFlush(store);
    }

    /**
     * 生成 仓库
     *
     * @param branchEntry
     */
    public Depot setDepot(BranchEntry branchEntry, Dept dept) {
        //逻辑仓库
        Depot depot = new Depot();
        depot.setName(branchEntry.getName());
        depot.setCompany(branchEntry.getCompany());
        depot.setDisplayName(branchEntry.getName());
        depot.setValid(branchEntry.isValid());
        depot.setOrigin(branchEntry.getCode());
        depot.setDepotLevel(enumerationRepository.findByTypeAndValue("门店", "depotLevel"));
        depot.setDept(dept);
        depot.setId(depot.obtainDepotId(depot));
        return depotRepository.saveAndFlush(depot);
    }

    /**
     * 写入物理仓库
     *
     * @param store
     * @return PhyDepot
     */
    public PhyDepot setPhyDepot(Store store) {
        //物理仓库
        PhyDepot phyDepot = new PhyDepot();
        phyDepot.setName(store.getName());
        phyDepot.setCountry(store.getCountry());
        phyDepot.setProvince(store.getProvince());
        phyDepot.setCity(store.getCity());
        phyDepot.setCounty(store.getCounty());
        phyDepot.setAddress(store.getAddress());
        if (store.getWarehouse() != null) {
            phyDepot.setArea(Double.valueOf(store.getWarehouse()));
        }
        phyDepot.setPhone(store.getTelephone());
        phyDepot.setLatitude(store.getLatitude());//纬度
        phyDepot.setLongitude(store.getLongitude());//经度
        phyDepot.setOrigin(store.getCode());
        return SpringManager.getBean(PhyDepotRepository.class).saveAndFlush(phyDepot);
    }

    /**
     * 写入库区
     *
     * @param branchEntry
     * @param depot
     * @param phyDepot
     * @return locations
     */
    public List<Location> setLocations(BranchEntry branchEntry, Depot depot, PhyDepot phyDepot) {
        List<Location> locations = new ArrayList<>();
        branchEntry.getUsageList().forEach(stockUsage -> {
            Location location = new Location();
            String name = branchEntry.getName() + stockUsage.getName();
            location.setCompany(branchEntry.getCompany());
            location.setName(name);
            location.setDepot(depot);
            location.setPhyDepot(phyDepot);
            location.setUsage(stockUsage);
            location.setSalesAutoDelivery(true);
            location.setValid(true);
            location.setId(location.obtainLocationId(location));
            Location result = locationRepository.saveAndFlush(location);
            result.setOrigin(result.getId());
            locationRepository.saveAndFlush(result);
            locations.add(result);
        });
        return locations;
    }

    /**
     * 生成本地权限 和 本地角色
     *
     * @param branchEntry
     */
    public void setLocalPermit(BranchEntry branchEntry) {
        String topic = "event:cm.branchEntry.setLocalPermit";
        EventUtil.sendSynEvent(this, topic, branchEntry);
    }

    /**
     * 生成成本中心 和 利润中心
     *
     * @param branchEntry
     */
    public void setDutyCenter(BranchEntry branchEntry, Dept dept) {
//            DutyCenter dutyCenter = new DutyCenter();
//            dutyCenter.setCenterType(enumeration);
//            dutyCenter.setCompany(branchEntry.getCompany());
//            dutyCenter.setName(branchEntry.getName());
//            dutyCenter.setValid(true);
//            dutyCenterRepository.saveAndFlush(dutyCenter);
    }

    /**
     * 写入库区信息
     *
     * @param branchEntry
     * @param locations
     * @param result
     * @return result
     */
    private JSONObject writeLocations(BranchEntry branchEntry, List<Location> locations, JSONObject result) {
        JSONArray array = new JSONArray();
        // 同步 仓库库区信息 （旧框架的 MAS_CKKQ 表）
        //根据当前公司查找门店
        List<Store> stores = storeRepository.findAll(JpaDsl.toCriteriaByEq("company.id", branchEntry.getCompany().getId()));
        if (stores.size() == 1) {
            //当入驻第一家门店时 产生退货周转库及其逻辑仓
            //逻辑仓库
            Depot depot = new Depot();
            depot.setName(branchEntry.getCompany().getName() + "总仓");
            depot.setCompany(branchEntry.getCompany());
            depot.setDisplayName(branchEntry.getCompany().getName() + "总仓");
            depot.setValid(branchEntry.isValid());
            depot.setOrigin(branchEntry.getCode());
            depot.setDepotLevel(enumerationRepository.findByTypeAndValue("门店", "depotLevel"));
            depot.setDept(locations.stream().findFirst().get().getDepot().getDept());
            depot.setId(depot.obtainDepotId(depot));
            depotRepository.saveAndFlush(depot);
            //退货周转仓
            Location locationReturn = new Location();
            String name = branchEntry.getCompany().getName() + "退货周转仓";
            locationReturn.setCompany(branchEntry.getCompany());
            locationReturn.setName(name);
            locationReturn.setDepot(depot);
            StockUsage stockUsage = new StockUsage();
            stockUsage.setId("8");
            locationReturn.setUsage(stockUsage);
            locationReturn.setSalesAutoDelivery(true);
            locationReturn.setValid(true);
            locationReturn.setOrigin("1001" + "BX01" + branchEntry.getCode() + "8");
            locationReturn.setId(locationReturn.obtainLocationId(locationReturn));
            locationRepository.saveAndFlush(locationReturn);
            JSONObject synZZCKKQ = new JSONObject();
            synZZCKKQ.put("CKKQID", locationReturn.getId());
            synZZCKKQ.put("CKKQMC", locationReturn.getName());
            synZZCKKQ.put("CKID", branchEntry.getCode());
            synZZCKKQ.put("CKMC", branchEntry.getName());
            synZZCKKQ.put("KQID", locationReturn.getUsage().getId());
            synZZCKKQ.put("KQMC", "退货周转库");
            synZZCKKQ.put("CCTJID", "10");//存储条件只有一个常温
            synZZCKKQ.put("CCTJMC", "常温");
            synZZCKKQ.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
            synZZCKKQ.put("LRR", "admin");
            synZZCKKQ.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
            synZZCKKQ.put("FMFS", 0);
            synZZCKKQ.put("XNCBJ", 0);
            synZZCKKQ.put("YSCKBJ", 0);
            synZZCKKQ.put("ZDCKBJ", 0);
            synZZCKKQ.put("GSID", branchEntry.getCompany().getId());
            synZZCKKQ.put("GSMC", branchEntry.getCompany().getName());
            synZZCKKQ.put("DDID", branchEntry.getCode());
            synZZCKKQ.put("DDMC", branchEntry.getName());
            synZZCKKQ.put("WD", branchEntry.getLatitude());
            synZZCKKQ.put("JD", branchEntry.getLongitude());
            if ("001073".equals(branchEntry.getCompany().getParty().getCorporate().getOperation().getId())) {
                synZZCKKQ.put("XNCK", "1001" + "BX01" + branchEntry.getCode() + "8");
            }
            array.add(synZZCKKQ);
            // 同步 DC配送范围 （旧框架的 MAS_DCPSFW 表）
            JSONObject synTHDCPSFW = new JSONObject();
            synTHDCPSFW.put("CGZZID", "1001");
            synTHDCPSFW.put("CGZZMC", "广州市集群车宝汽车服务连锁有限公司");
            synTHDCPSFW.put("FCKKQID", "1001BX01X011");
            synTHDCPSFW.put("FCKKQMC", "广州配送中心正常库");
            synTHDCPSFW.put("ZCKID", branchEntry.getCode());
            synTHDCPSFW.put("ZCKMC", branchEntry.getName());
            synTHDCPSFW.put("ZDR", "admin");
            synTHDCPSFW.put("ZDRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
            synTHDCPSFW.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
            synTHDCPSFW.put("FCKID", "BX01");
            synTHDCPSFW.put("FCKMC", "广州配送中心");
            synTHDCPSFW.put("FKQID", "1");
            synTHDCPSFW.put("FKQMC", "正常库");
            synTHDCPSFW.put("ZDPHBJ", 1);
            synTHDCPSFW.put("ZCKKQID", locationReturn.getId());
            synTHDCPSFW.put("ZCKKQMC", locationReturn.getName());
            synTHDCPSFW.put("ZKQID", "8");
            synTHDCPSFW.put("ZKQMC", "退货周转库");
            result.put("THDCPSFW", synTHDCPSFW);
        }
        locations.forEach(location -> {
            JSONObject synCKKQ = new JSONObject();
            synCKKQ.put("CKKQID", location.getId());
            synCKKQ.put("CKKQMC", location.getName());
            synCKKQ.put("CKID", branchEntry.getCode());
            synCKKQ.put("CKMC", branchEntry.getName());
            synCKKQ.put("KQID", location.getUsage().getId());
            synCKKQ.put("KQMC", location.getUsage().getName());
            synCKKQ.put("CCTJID", "10");//存储条件只有一个常温
            synCKKQ.put("CCTJMC", "常温");
            synCKKQ.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
            synCKKQ.put("LRR", "admin");
            synCKKQ.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
            synCKKQ.put("FMFS", 0);
            synCKKQ.put("XNCBJ", 0);
            synCKKQ.put("YSCKBJ", 0);
            synCKKQ.put("ZDCKBJ", 0);
            synCKKQ.put("GSID", branchEntry.getCompany().getId());
            synCKKQ.put("GSMC", branchEntry.getCompany().getName());
            synCKKQ.put("DDID", branchEntry.getCode());
            synCKKQ.put("DDMC", branchEntry.getName());
            synCKKQ.put("WD", branchEntry.getLatitude());
            synCKKQ.put("JD", branchEntry.getLongitude());
            if ("001073".equals(branchEntry.getCompany().getParty().getCorporate().getOperation().getId())) {
                //绑定第一家虚拟仓库
                if (stores.size() == 1) {
                    synCKKQ.put("XNCK", "1001" + "BX01" + branchEntry.getCode() + "8");
                } else {
                    synCKKQ.put("MDID", stores.stream().filter(s -> !s.getId().equals(branchEntry.getDeptId())).findFirst().get().getCode());
                }
            }
//            String CKKQtopic = "event:cm.branchEntry.synCKKQ";
//            Boolean CKKQflg = (Boolean) EventUtil.sendSynEvent(this, CKKQtopic, synCKKQ).stream().findFirst().get();
//            if (!CKKQflg) {
//                throw new RuntimeException("同步仓库库区信息到旧框架时报错!");
//            }
            //将库区信息添加至返回值
            array.add(synCKKQ);

            if (location.getUsage().getName().equals("正常库")) {
                // 同步 DC配送范围 （旧框架的 MAS_DCPSFW 表）
                JSONObject synDCPSFW = new JSONObject();
                synDCPSFW.put("CGZZID", "1001");
                synDCPSFW.put("CGZZMC", "广州市集群车宝汽车服务连锁有限公司");
                synDCPSFW.put("FCKKQID", "1001BX01X011");
                synDCPSFW.put("FCKKQMC", "广州配送中心正常库");
                synDCPSFW.put("ZCKID", branchEntry.getCode());
                synDCPSFW.put("ZCKMC", branchEntry.getName());
                synDCPSFW.put("ZDR", "admin");
                synDCPSFW.put("ZDRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synDCPSFW.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synDCPSFW.put("FCKID", "BX01");
                synDCPSFW.put("FCKMC", "广州配送中心");
                synDCPSFW.put("FKQID", "1");
                synDCPSFW.put("FKQMC", "正常库");
                synDCPSFW.put("ZDPHBJ", 1);
                synDCPSFW.put("ZCKKQID", location.getId());
                synDCPSFW.put("ZCKKQMC", location.getName());
                synDCPSFW.put("ZKQID", "1");
                synDCPSFW.put("ZKQMC", "正常库");

//                String DCPSFWtopic = "event:cm.branchEntry.synDCPSFW";
//                Boolean DCPSFWflg = (Boolean) EventUtil.sendSynEvent(this, DCPSFWtopic, synDCPSFW).stream().findFirst().get();
//                if (!DCPSFWflg) {
//                    throw new RuntimeException("同步DC配送范围信息到旧框架时报错!");
//                }
                result.put("DCPSFW", synDCPSFW);
            }
        });
        result.put("CKKQ", array);
        return result;
    }

    /**
     * 写入部门信息
     *
     * @param branchEntry
     * @param branch
     * @param result
     * @return result
     */
    private JSONObject writeBranch(BranchEntry branchEntry, Branch branch, JSONObject result) {
        // 同步到旧框架 部门信息
        JSONObject synBMXX = new JSONObject();
        synBMXX.put("BMID", branch.getId());
        synBMXX.put("BMMC", branchEntry.getName());
        synBMXX.put("GSID", branchEntry.getCompany().getId());
        synBMXX.put("GSMC", branchEntry.getCompany().getName());
        synBMXX.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synBMXX.put("LRR", "admin");
        synBMXX.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
//        String topic = "event:cm.branchEntry.synBMXX";
//        Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synBMXX).stream().findFirst().get();
//        if (!flg) {
//            throw new RuntimeException("同步部门信息到旧框架时报错!");
//        }
        result.put("BMXX", synBMXX);
        return result;
    }

    /**
     * 写入地点信息
     *
     * @param branchEntry
     * @param result
     * @return
     */
    private JSONObject writeLocation(BranchEntry branchEntry, JSONObject result) {
        // 同步 地点信息 （先有地点信息 再有 门店信息）
        JSONObject synDDXX = new JSONObject();
        synDDXX.put("DDID", branchEntry.getCode());
        synDDXX.put("DDMC", branchEntry.getName());
        synDDXX.put("GSID", branchEntry.getCompany().getId());
        synDDXX.put("GSMC", branchEntry.getCompany().getName());
        synDDXX.put("CKBJ", 1);
        synDDXX.put("MDBJ", 1);
        synDDXX.put("YXBJ", 1);
        synDDXX.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synDDXX.put("LRR", "admin");
        synDDXX.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
        synDDXX.put("CKJB", 2);
        synDDXX.put("WLSKBJ", 0);
//        String DDtopic = "event:cm.branchEntry.synDDXX";
//        Boolean DDflg = (Boolean) EventUtil.sendSynEvent(this, DDtopic, synDDXX).stream().findFirst().get();
//        if (!DDflg) {
//            throw new RuntimeException("同步地点信息到旧框架时报错!");
//        }
        result.put("DDXX", synDDXX);
        return result;
    }

    /**
     * 写入门店信息 门店扩展信息
     *
     * @param branchEntry
     * @param store
     * @param result
     * @return result
     */
    private JSONObject writeStore(BranchEntry branchEntry, Store store, JSONObject result) {
        // 同步 门店信息
        JSONObject synMDXX = new JSONObject();
        synMDXX.put("MDID", branchEntry.getCode());
        synMDXX.put("MDMC", branchEntry.getName());
        synMDXX.put("MDMJ", branchEntry.getStoreSpace());
        synMDXX.put("GJID", branchEntry.getCountry().getId());
        synMDXX.put("SFID", store.getProvince().getId().substring(0, store.getProvince().getId().length() - 4));
        synMDXX.put("CSID", store.getCity().getId().substring(0, store.getCity().getId().length() - 2));
        synMDXX.put("QXID", store.getCounty().getId());
        synMDXX.put("GJMC", store.getCountry().getName());
        synMDXX.put("SFMC", store.getProvince().getName());
        synMDXX.put("CSMC", store.getCity().getName());
        synMDXX.put("QXMC", store.getCounty().getName());

        synMDXX.put("DZ", store.getAddress());
        synMDXX.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synMDXX.put("LRR", "admin");
        synMDXX.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
        synMDXX.put("GSID", branchEntry.getCompany().getId());
        synMDXX.put("GSMC", branchEntry.getCompany().getName());
        synMDXX.put("MDLXID", store.getStoreType().getCode());
        synMDXX.put("MDLXMC", store.getStoreType().getDescription());
        synMDXX.put("SQID", store.getBusinessCircle().getId());//枚举类型 显示code 等于 旧框架id
        synMDXX.put("SQMC", store.getBusinessCircle().getName());
        synMDXX.put("MDDJID", store.getBusinessCircle().getId());//枚举类型 显示code 等于 旧框架id
        synMDXX.put("MDDJMC", store.getBusinessCircle().getName());
        synMDXX.put("LXDH", store.getTelephone());
        if (branchEntry.getOpenDay() != null) {
            synMDXX.put("KYRQ", DateUtils.format(branchEntry.getOpenDay(), "yyyy-MM-dd"));
        }
//
//        String topic = "event:cm.branchEntry.synMDXX";
//        Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synMDXX).stream().findFirst().get();
//        if (!flg){
//            throw new RuntimeException("同步门店信息到旧框架时报错!");
//        }
        result.put("MDXX", synMDXX);
        // 同步 门店扩展信息
        JSONObject synMDKZXX = new JSONObject();
        synMDKZXX.put("MDID", branchEntry.getCode());
        synMDKZXX.put("MDMC", branchEntry.getName());
        synMDKZXX.put("JPJMJ", branchEntry.getBoutiqueRoom());
        synMDKZXX.put("GKMJ", branchEntry.getWarehouse());
        synMDKZXX.put("WZMJ", branchEntry.getRentalArea());
        synMDKZXX.put("JZMJ", branchEntry.getCalculationRental());
        if (branchEntry.getReceivingDay() != null) {
            synMDKZXX.put("JCSRQ_SJ", DateUtils.format(branchEntry.getReceivingDay(), "yyyy-MM-dd HH:mm:ss"));
        }
        if (branchEntry.getOpenDay() != null) {
            synMDKZXX.put("KYRQ_SJ", DateUtils.format(branchEntry.getOpenDay(), "yyyy-MM-dd HH:mm:ss"));
            synMDKZXX.put("KYRQ", DateUtils.format(branchEntry.getOpenDay(), "yyyy-MM-dd HH:mm:ss"));

        }
        synMDKZXX.put("HFCD", branchEntry.getBannerLength());
        synMDKZXX.put("LEDPCD", branchEntry.getLEDLength());

        synMDKZXX.put("ZXTR", branchEntry.getDecoration());
        synMDKZXX.put("SBTR", branchEntry.getEquipment());
        synMDKZXX.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synMDKZXX.put("LRR", "admin");
        synMDKZXX.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
//        String MDKZXXtopic = "event:cm.branchEntry.synMDKZXX";
//        Boolean MDKZXXflg = (Boolean) EventUtil.sendSynEvent(this, MDKZXXtopic, synMDKZXX).stream().findFirst().get();
//        if (!MDKZXXflg) {
//            throw new RuntimeException("同步门店扩展信息到旧框架时报错!");
//        }
        result.put("MDKZXX", synMDKZXX);
        return result;
    }

    /**
     * 写入仓库扩展信息
     *
     * @param branchEntry
     * @param result
     * @return result
     */
    private JSONObject writeWarehouse(BranchEntry branchEntry, Store store, JSONObject result) {
        // 同步 维护仓库扩展信息 （旧框架的 MAS_CKXX 表）
        JSONObject synCKXX = new JSONObject();
        synCKXX.put("CKID", branchEntry.getCode());
        synCKXX.put("CKMC", branchEntry.getName());
        synCKXX.put("GJID", store.getCountry().getId());
        synCKXX.put("SFID", store.getProvince().getId().substring(0, store.getProvince().getId().length() - 4));
        synCKXX.put("CSID", store.getCity().getId().substring(0, store.getCity().getId().length() - 2));
        synCKXX.put("QXID", store.getCounty().getId());
        synCKXX.put("DZ", store.getAddress());
        synCKXX.put("YXBJ", 1);
        synCKXX.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synCKXX.put("LRR", "admin");
        synCKXX.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
        if ((branchEntry.getOpenDay() != null)) {
            synCKXX.put("KYRQ", DateUtils.format(branchEntry.getOpenDay(), "yyyy-MM-dd HH:mm:ss"));
        }
        synCKXX.put("GSID", branchEntry.getCompany().getId());
        synCKXX.put("GSMC", branchEntry.getCompany().getName());
//
//        String CKXXtopic = "event:cm.branchEntry.synCKXX";
//        Boolean CKXXflg = (Boolean) EventUtil.sendSynEvent(this, CKXXtopic, synCKXX).stream().findFirst().get();
//        if (!CKXXflg) {
//            throw new RuntimeException("同步维护仓库扩展信息到旧框架时报错!");
//        }
        result.put("CKXX", synCKXX);
        return result;
    }

    /**
     * 写入采购信息
     *
     * @param branchEntry
     * @param result
     * @return result
     */
    private JSONObject writePurchase(BranchEntry branchEntry, JSONObject result) {
        //采购范围
        JSONObject synCGFW = new JSONObject();
        synCGFW.put("CGZZID", branchEntry.getCompany().getId());
        synCGFW.put("CGZZMC", branchEntry.getCompany().getName());
        synCGFW.put("CKID", branchEntry.getCode());
        synCGFW.put("CKMC", branchEntry.getName());
        synCGFW.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synCGFW.put("LRR", "admin");
        synCGFW.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
//
//        String CGFWtopic = "event:cm.branchEntry.synCGFW";
//        Boolean CGFWflg = (Boolean) EventUtil.sendSynEvent(this, CGFWtopic, synCGFW).stream().findFirst().get();
//        if (!CGFWflg) {
//            throw new RuntimeException("同步采购范围信息到旧框架时报错!");
//        }
        result.put("CGFW", synCGFW);

        //采购商品组
        JSONObject synCGSPZ = new JSONObject();
        synCGSPZ.put("GSID", branchEntry.getCompany().getId());
        synCGSPZ.put("GSMC", branchEntry.getCompany().getName());
        synCGSPZ.put("SPZID", branchEntry.getDeptId());
        synCGSPZ.put("SPZMC", branchEntry.getName());
        synCGSPZ.put("CGZZID", branchEntry.getCompany().getId());
        synCGSPZ.put("CGZZMC", branchEntry.getCompany().getName());
        synCGSPZ.put("YXBJ", 1);
        synCGSPZ.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
        synCGSPZ.put("LRR", "admin");
        synCGSPZ.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
//
//        String CGSPZtopic = "event:cm.branchEntry.synCGSPZ";
//        Boolean CGSPZflg = (Boolean) EventUtil.sendSynEvent(this, CGSPZtopic, synCGSPZ).stream().findFirst().get();
//        if (!CGSPZflg) {
//            throw new RuntimeException("同步采购商品组信息到旧框架时报错!");
//        }
        result.put("CGSPZ", synCGSPZ);
        return result;
    }

    /**
     * 写入成本中心 和 利润中心
     *
     * @param branchEntry
     * @param dept
     * @param result
     * @return result
     */
    public JSONObject writeDutyCenter(BranchEntry branchEntry, Dept dept, JSONObject result) {
        enumerationRepository.findByType("respCenterType").forEach(enumeration -> {
            String id = branchEntry.getCompany().getId() + "00" + dept.getId();
            if (enumeration.getDescription().equals("成本中心")) {
                JSONObject synCBZX = new JSONObject();
                synCBZX.put("CBZXID", id);
                synCBZX.put("CBZXMC", branchEntry.getName());
                synCBZX.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synCBZX.put("LRR", "admin");
                synCBZX.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synCBZX.put("YXBJ", 1);
                synCBZX.put("CBZXLXID", "S");
                synCBZX.put("CBZXLXMC", "销售");
                synCBZX.put("GSID", branchEntry.getCompany().getId());
//                String CBZXtopic = "event:cm.branchEntry.synCBZX";
//                Boolean CBZXflg = (Boolean) EventUtil.sendSynEvent(this, CBZXtopic, synCBZX).stream().findFirst().get();
//                if (!CBZXflg) {
//                    throw new RuntimeException("同步成本中心信息到旧框架时报错!");
//                }
                result.put("CBZX", synCBZX);
            } else {
                JSONObject synLRZX = new JSONObject();
                synLRZX.put("LRZXID", id);
                synLRZX.put("LRZXMC", branchEntry.getName());
                synLRZX.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synLRZX.put("LRR", "admin");
                synLRZX.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synLRZX.put("YXBJ", 1);
                synLRZX.put("GSID", branchEntry.getCompany().getId());
//                String LRZXtopic = "event:cm.branchEntry.synLRZX";
//                Boolean LRZXflg = (Boolean) EventUtil.sendSynEvent(this, LRZXtopic, synLRZX).stream().findFirst().get();
//                if (!LRZXflg) {
//                    throw new RuntimeException("同步利润中心信息到旧框架时报错!");
//                }
                result.put("LRZX", synLRZX);

                JSONObject synDDZRZX = new JSONObject();
                synDDZRZX.put("DDID", branchEntry.getCode());
                synDDZRZX.put("DDMC", branchEntry.getName());
                synDDZRZX.put("GSID", branchEntry.getCompany().getId());
                synDDZRZX.put("GSMC", branchEntry.getCompany().getName());
                synDDZRZX.put("CBZXID", id);
                synDDZRZX.put("CBZXMC", branchEntry.getName());
                synDDZRZX.put("LRZXID", id);
                synDDZRZX.put("LRZXMC", branchEntry.getName());
                synDDZRZX.put("TS01", DateUtils.format(branchEntry.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synDDZRZX.put("LRR", "admin");
                synDDZRZX.put("LRRQ_SJ", DateUtils.format(branchEntry.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synDDZRZX.put("YXBJ", 1);
//                String DDZRZXtopic = "event:cm.branchEntry.synDDZRZX";
//                Boolean DDZRZXflg = (Boolean) EventUtil.sendSynEvent(this, DDZRZXtopic, synDDZRZX).stream().findFirst().get();
//                if (!DDZRZXflg) {
//                    throw new RuntimeException("同步地点配置责任中心信息到旧框架时报错!");
//                }
                result.put("DDZRZX", synDDZRZX);
            }
        });

        return result;
    }

    /**
     * 写入销售组织门店
     * @param branchEntry
     * @param store
     * @param result
     * @return
     */
    public JSONObject writeSalesStore(BranchEntry branchEntry, Store store, JSONObject result) {
        JSONObject synXSZZ = new JSONObject();
        synXSZZ.put("XSZZID", branchEntry.getCompany().getId());
        synXSZZ.put("XSZZMC", branchEntry.getCompany().getName());
        synXSZZ.put("LRR", "admin");
        synXSZZ.put("MDID", store.getOrigin());
        synXSZZ.put("MDMC", store.getName());
        result.put("XSZZMD",synXSZZ);
        return result;
    }

    /**
     * 推送同步消息至老系统
     *
     * @param body
     */
    private void synUnifiedExport(JSONObject body) {
        String topic = "event:cm.branchEntry.synUnifiedExport";
        EventUtil.sendSynEvent(this, topic, body).stream().findFirst().get();
    }

    /**
     * 推送异步消息至老系统
     *
     * @param request
     */
    @Consumer(topic = "mq.branch.unified.export")
    private void mqUnifiedExport(SimpleRequest request) {
        String topic = "event:cm.branchEntry.synUnifiedExport";
        EventUtil.sendSynEvent(this, topic, request.getJO()).stream().findFirst().get();
    }
}
